<?php

namespace app\models;

use app\utils\EncryptUtils;
use yii;
use app\components\BaseActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property integer $id
 * @property integer $type
 * @property string $uname
 * @property string $avatar
 * @property string $phone
 * @property string $password
 * @property string remark
 * @property integer $status
 * @property integer $ctime
 *
 * @property UserPlatform $platform
 * @property UserProfile $profile
 */
class User extends BaseActiveRecord implements yii\web\IdentityInterface {

    const STATUS_ACTIVE = 1;
    const STATUS_DISABLE = 2;
    const STATUS_VERIFY = 3;
    const STATUS_VERIFY_DENY = 4;

    const TYPE_STUDENT = 1;
    const TYPE_ORG = 2;
    const TYPE_COMPANY = 3;

    public static $userTypeLabels = [
        self::TYPE_STUDENT => '大学生',
        self::TYPE_ORG => '社会组织',
        self::TYPE_COMPANY => '企业',
        0 => '未完善身份'
    ];

    public static $userNameLabels = [
        self::TYPE_STUDENT => '姓名',
        self::TYPE_ORG => '社会组织',
        self::TYPE_COMPANY => '企业名称',
    ];

    public static $statusLabels = [
        self::STATUS_ACTIVE => '正常',
        self::STATUS_DISABLE => '停用',
        self::STATUS_VERIFY => '待审核',
        self::STATUS_VERIFY_DENY => '审核未通过',
    ];

    public static $statusColors = [
        self::STATUS_VERIFY => 'warning',
        self::STATUS_VERIFY_DENY => 'danger',
        self::STATUS_ACTIVE => 'success',
        self::STATUS_DISABLE => 'danger',
    ];

    const rememberTime = 259200;

    public $verifyCode, $password1;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['password1'], 'compare', 'compareAttribute' => 'password', 'message' => '2次密码不一致', 'on' => 'register'],

            [['type', 'phone', 'uname', 'verifyCode'], 'required', 'on' => 'identity'],

            [['type', 'phone'], 'required', 'on' => 'save'],
            ['phone', 'unique'],
            [['phone', 'password', 'password1', 'verifyCode'], 'required', 'on' => 'register'],
            [['phone', 'password'], 'required', 'on' => 'login'],

            ['verifyCode', 'integer'],
            ['verifyCode', 'validateSms', 'skipOnEmpty' => TRUE],

            [['type', 'status', 'ctime'], 'integer'],
            [['uname', 'avatar', 'remark'], 'string', 'max' => 160],
            [['phone'], 'string', 'max' => 11],
            [['password', 'password1'], 'string', 'max' => 16],
            ['type', 'in', 'range' => [static::TYPE_STUDENT, static::TYPE_ORG, static::TYPE_COMPANY]],
        ];
    }

    public function validateSms() {
        $sms = new Sms();
        $res = $sms->verify($this->phone, $this->verifyCode);
        if ($res['code'] != 0) {
            $this->addError('verifyCode', $res['msg']);
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'type' => '用户类型',
            'uname' => '昵称',
            'phone' => '手机号',
            'password' => '密码',
            'avatar' => '头像',
            'status' => '状态',
            'ctime' => '注册时间',
            'verifyCode' => '短信验证码'
        ];
    }

    /**
     * Finds an identity by the given ID.
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id) {
        return static::findOne($id);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = NULL) {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|integer an ID that uniquely identifies a user identity.
     */
    public function getId() {
        return $this->id;
    }

    public function getAuthKey() {
        return EncryptUtils::md516(APP_KEY);
    }

    public function validateAuthKey($authKey) {
        return EncryptUtils::md516(APP_KEY) === $authKey;
    }

    public function getProfile() {
        return $this->hasOne(UserProfile::className(), ['uid' => 'id']);
    }

    public function afterSave($insert, $changedAttributes) {
        if ($insert && !$this->profile) {
            $profile = new UserProfile();
            $profile->uid = $this->id;
            $profile->save(FALSE);
        }

        parent::afterSave($insert, $changedAttributes);
    }

    public function registerByPhone() {
        $this->status = 0;
        $this->password = EncryptUtils::md516($this->password);
        $this->password1 = EncryptUtils::md516($this->password1);
        $this->uname = $this->phone;
        $res = $this->save();
        if ($res['code'] != 0) {
            return $res;
        }

        Yii::$app->user->login($this, self::rememberTime);
        return $res;
    }

    public function loginByPhone() {
        /* @var $user User */
        $user = User::findOne(['phone' => $this->phone]);
        if (!$user) {
            return static::retErr('手机号未注册');
        }

        $_pass = EncryptUtils::md516($this->password);
        if ($user->password !== $_pass) {
            return static::retErr('密码错误');
        }
        if ($user->getIsDisabled()) {
            return static::retErr('账号异常,请联系客服.');
        }

        Yii::$app->user->login($user, self::rememberTime);

        return static::retOK();
    }

    public function resetPwd() {
        $user = static::findOne(['phone' => $this->phone]);
        if (!$user) {
            return static::retErr('操作错误');
        }

        $user->verifyCode = $this->verifyCode;
        $user->setScenario('register');

        $user->password = EncryptUtils::md516($this->password);
        $user->password1 = EncryptUtils::md516($this->password1);
        return $user->save();
    }

    public function getIsActive() {
        return intval($this->status) === intval(self::STATUS_ACTIVE);
    }

    public function getIsVerify() {
        return intval($this->status) === intval(self::STATUS_VERIFY);
    }

    public function getIsVerifyDeny() {
        return intval($this->status) === intval(self::STATUS_VERIFY_DENY);
    }

    public function getIsDisabled() {
        return intval($this->status) === intval(self::STATUS_DISABLE);
    }

    public function getIsStudent() {
        return intval($this->type) === intval(self::TYPE_STUDENT);
    }

    public function getIsCompany() {
        return intval($this->type) === intval(self::TYPE_COMPANY);
    }

    public function getUserTypeLabel() {
        return static::$userTypeLabels[$this->type];
    }

    public function loginCookie(IdentityInterface $identity = NULL) {
        if (NULL === $identity) {
            $identity = $this;
        }
        Yii::$app->user->login($identity, self::rememberTime);
    }

}
